<template>
  <div class="role-container">
    <!-- 添加按钮 -->
    <el-button type="primary" @click="isShow=true">添加角色</el-button>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
    >
      <!-- 角色列 -->
      <el-table-column
        prop="name"
        label="角色"
        width="180"
      >
        <template v-slot="{row}">
          <!-- 编辑 -->
          <template v-if="row.isEdit">
            <el-input v-model="editForm.name"></el-input>
          </template>
          <!-- 正常 -->
          <template v-else>
            <div>{{ row.name }}</div>
          </template>
        </template>
      </el-table-column>
      <!-- 启用列 -->
      <el-table-column
        label="启用"
        width="180"
      >
        <template v-slot="{row}">
          <!-- 编辑 -->
          <template v-if="row.isEdit">
            <el-switch
              v-model="editForm.state"
              :active-value="1"
              :inactive-value="0"
              active-color="#409eff"
            >
            </el-switch></template>
          <!-- 正常 -->
          <template v-else>
            {{ row.state?'已启用':'未启用' }}
          </template>
        </template>
      </el-table-column>
      <!-- 描述列 -->
      <el-table-column
        prop="description"
        label="描述"
      >
        <template v-slot="{row}">
          <!-- 编辑 -->
          <template v-if="row.isEdit">
            <el-input v-model="editForm.description"></el-input>
          </template>
          <!-- 正常 -->
          <template v-else>
            <div>{{ row.description }}</div>
          </template>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column
        label="操作"
      >
        <template v-slot="{row}">
          <!-- 编辑 -->
          <template v-if="row.isEdit">
            <el-button type="primary" @click="editSubmit">确认</el-button>
            <el-button @click="row.isEdit=false">取消</el-button>
          </template>
          <!-- 正常 -->
          <template v-else>
            <el-button type="text" size="small">分配权限</el-button>
            <el-button class="btnEdit" type="text" size="small" @click="editRow(row)">编辑</el-button>
            <el-popconfirm
              title="这是一段内容确定删除吗？"
              @onConfirm="removeRole(row.id)"
            >
              <el-button slot="reference" type="text" size="small">删除</el-button>
            </el-popconfirm>
          </template>

        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      :total="total"
      :page-size="pagesize"
      layout="total,prev, pager, next"
      @current-change="currentChange"
    >
    </el-pagination>

    <!-- 弹窗 -->
    <el-dialog title="新增角色" :visible.sync="isShow" @close="closeDialog">
      <el-form ref="formRef" :model="addForm" :rules="addFromRules">
        <el-form-item label="角色名称" :label-width="'120px'" prop="name">
          <el-input v-model="addForm.name" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="启用" :label-width="'120px'">
          <el-switch
            v-model="addForm.state"
            :active-value="1"
            :inactive-value="0"
            active-color="#409eff"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="'120px'" prop="description">
          <el-input v-model="addForm.description" type="textarea" placeholder="1-100个字符" />
        </el-form-item>
        <el-form-item :label-width="'120px'">
          <el-button type="primary" @click="onSubmit">确 定</el-button>
          <el-button @click="resetForm">重 置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleRequest, addRoleRequest, removeRoleRequest, updateRoleRequest } from '@/api/role'
export default {
  name: 'Role',
  data() {
    // 角色名业务校验
    const roleNameValidate = (rule, value, callback) => {
      if (this.tableData.some(item => item.name === value)) callback(new Error('角色已存在'))
      else callback()
    }
    return {
      isShow: false, // 对话框
      // 弹框表单
      addForm: {
        state: 0,
        name: '',
        description: ''
      },
      // 校验
      addFromRules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '名称必须2-10个字符', trigger: 'blur' },
          {
            validator: roleNameValidate,
            trigger: 'blur'
          }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '名称必须1-100个字符', trigger: 'blur' }
        ]
      },
      // 编辑表单
      editForm: {},
      page: 1,
      pagesize: 5,
      tableData: [],
      total: 0
    }
  },
  created() {
    this.getRole()
  },
  methods: {
    // 请求列表
    async getRole() {
      const res = await getRoleRequest(this._data)
      this.total = res.data.total
      // 为每一项添加isEdit属性
      this.tableData = res.data.rows.map(item => {
        item.isEdit = false
        return item
      })
    },
    // 分页变化时触发
    currentChange(val) {
      this.page = val
      this.getRole()
    },
    // 关闭弹窗时
    closeDialog() {
      this.isShow = false
      this.resetForm()
    },
    // 表单提交
    async onSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          await addRoleRequest(this.addForm)
          this.$message.success('添加成功')
          this.isShow = false
          this.getRole()
        }
      })
    },
    // 重置表单
    resetForm() {
      this.$refs.formRef.resetFields()
      this.addForm.state = 0
    },
    // 删除
    async removeRole(id) {
      try {
        await removeRoleRequest(id)
        this.$message.success('删除成功')
        // 判断是否是当前页最后一项
        if (this.tableData.length === 1 && this.page > 1) {
          this.page--
        }
      } catch (error) {
        console.log('删除失败')
      }
      this.getRole()
    },
    // 切换编辑
    editRow(row) {
      this.tableData.forEach(item => { item.isEdit = false })
      row.isEdit = true
      this.editForm = { ...row }
      console.log(row)
    },
    // 提交编辑
    async editSubmit() {
      try {
        await updateRoleRequest(this.editForm)
        this.$message.success('编辑成功')
        this.getRole()
      } catch (error) {
        //
      }
    }
  }
}

</script>

<style lang="scss" scoped>
.role-container{
  padding: 30px;
  // 表格组件
  .el-table{
    margin: 20px 0;
    .btnEdit{
      margin: 0 10px;
    }
  }
  // 分页组件
  .el-pagination{
    text-align: right;
  }
}

</style>
